package com.whisper.hfdp.mq.order;

import com.whisper.hfdp.mq.MqConstant;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class OrderProducer {
    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer(MqConstant.GROUP);
        producer.setNamesrvAddr(MqConstant.NAMESRV_ADDR);
        producer.start();

        List<OrderStep> orderList = createOrderList();
        for (OrderStep orderStep : orderList) {
            String body = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + ":" + orderStep.getOrderId() + ":" + orderStep.getStep();

            Message message = new Message(MqConstant.TOPIC, orderStep.getTag(), body.getBytes(StandardCharsets.UTF_8));
            SendResult sendResult = producer.send(message, (mqs, msg, arg) -> {
                int queueIndex = orderStep.getOrderId() % mqs.size();
                return mqs.get(queueIndex);
            }, orderStep.getOrderId());
            System.out.println(sendResult);
        }
        producer.shutdown();
    }

    @Data
    @AllArgsConstructor
    private static class OrderStep {
        private Integer orderId;

        private String step;

        private String tag;
    }

    private static List<OrderStep> createOrderList() {
        List<OrderStep> orderSteps = new ArrayList<>();
        orderSteps.add(new OrderStep(123456, "创建", "create"));
        orderSteps.add(new OrderStep(123456, "付款", "pay"));
        orderSteps.add(new OrderStep(123456, "发货", "ship"));
        orderSteps.add(new OrderStep(123456, "收货", "receipt"));
        orderSteps.add(new OrderStep(123456, "完成", "finish"));

        orderSteps.add(new OrderStep(456798, "创建", "create"));
        orderSteps.add(new OrderStep(456798, "付款", "pay"));
        orderSteps.add(new OrderStep(456798, "发货", "ship"));
        orderSteps.add(new OrderStep(456798, "收货", "receipt"));
        orderSteps.add(new OrderStep(456798, "完成", "finish"));

        orderSteps.add(new OrderStep(123789, "创建", "create"));
        orderSteps.add(new OrderStep(123789, "付款", "pay"));
        orderSteps.add(new OrderStep(123789, "发货", "ship"));
        orderSteps.add(new OrderStep(123789, "收货", "receipt"));
        orderSteps.add(new OrderStep(123789, "完成", "finish"));

        return orderSteps;
    }
}
